package advanced.io;

import java.io.*;

public class FileUtils {
    static String rootPath = "C:\\Users\\DMLYS\\Documents\\prepare_for_work\\pfw\\java_l\\src\\main\\java\\primary\\io";

    public static void main(String[] args) throws FileNotFoundException {

        InputStream is = new FileInputStream(rootPath + "/abc");
        FileOutputStream fileOutputStream = new FileOutputStream(rootPath + "/abc.bak");
        copy(is, fileOutputStream);
    }

    /**
     * 拷贝字符文件
     *
     * @param is
     * @param os
     */
    public static void copy(InputStream is, OutputStream os) {

        byte[] flush = new byte[1024];
        int len = -1;
        try {
            while ((len = is.read(flush)) != -1) {
                os.write(flush, 0, len);//分段写出
            }
            os.flush();
        } catch (IOException e) {

        } finally {
            close(is, os);//关闭资源
        }

    }

    /**
     * 定义可变参数的可关闭对象参数
     * 关闭所有可关闭对象
     *
     * @param io
     */
    public static void close(Closeable... io) {
        for (Closeable cl : io) {
            try {
                if (cl != null) cl.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*对输入输出流进行自动关闭

    try with resource
    */
    public static void copyAutoCloseResource(InputStream is, OutputStream os) {

        byte[] flush = new byte[1024];
        int len = -1;
        try (is; os) {
            while ((len = is.read(flush)) != -1) {
                os.write(flush, 0, len);//分段写出
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
